package com.jia.lightrailsystem

import android.annotation.SuppressLint
import android.bluetooth.BluetoothClass.Device
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.jia.lightrailsystem.bean.CreateNote
import com.jia.lightrailsystem.bean.DeviceInitData
import com.jia.lightrailsystem.bean.RfidBean
import com.jia.lightrailsystem.bean.UpdateNote
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.internal.Util
import priv.songxusheng.easystorer.EasyStorer
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * 扩展函数：简化网络请求回调处理
 */
private fun <T> Call<T>.enqueueWithCallback(
    onSuccess: (T) -> Unit,
    onError: (String) -> Unit
) {
    this.enqueue(object : Callback<T> {
        override fun onResponse(call: Call<T>, response: Response<T>) {
            if (response.isSuccessful) {
                response.body()?.let { onSuccess(it) } ?: onError("响应体为空")
            } else {
                onError("请求失败: ${response.code()}")
            }
        }

        override fun onFailure(call: Call<T>, t: Throwable) {
            onError("网络请求失败: ${t.message}")
        }
    })
}

object Http {

//    private val URL ="https://mengchuangcloud.com"
//    const val apiToken = "apiToken"

    private var apiService: ApiService? = null
//    private var COOKIE: String? = null
    private var TOKEN: String? = null
    fun httpInit(URL: String) {
        val retrofit = Retrofit.Builder() /*必须以  '/'  结束*/
            .baseUrl(URL) /*将返回的数据转换为Gson*/
            .addConverterFactory(GsonConverterFactory.create())
            .client(getClient())
            .build()


        /* 需要写一个专门的接口类 */
        apiService = retrofit.create(ApiService::class.java)


    }

//    //第一步
//    //接收拦截器  获取Cookie
//
//    class ReceivedCookiesInterceptor : Interceptor {
//        @Throws(IOException::class)
//        override fun intercept(chain: Chain): okhttp3.Response {
//            val originalResponse: okhttp3.Response = chain.proceed(chain.request())
//            LogUtils.e("原始请求头", originalResponse.headers().toString())
//
//            if (originalResponse.headers("Set-Cookie").isNotEmpty()) {
//                // 解析 Cookie
//                for (header in originalResponse.headers("Set-Cookie")) {
//                    // 使用实际的 Cookie 名称进行匹配
//                    if (header.startsWith("sessioncookiename")) {
//                        COOKIE = header.substringAfter("sessioncookiename=")
//                            .substringBefore(";")
//                    }
//                }
//            }
//            return originalResponse
//        }
//    }

    //第二步
    //发送拦截器  添加Cookie到请求头
    class AddCookiesInterceptor : Interceptor {
        @SuppressLint("SuspiciousIndentation")
        @Throws(IOException::class)
        override fun intercept(chain: Chain): okhttp3.Response {
            val builder: Request.Builder = chain.request().newBuilder()
            return chain.proceed(builder.build())
        }
    }


    //第三步 OkHttpClient.Builder添加上面的两个拦截器
    private fun getClient(): OkHttpClient {
        val okBuilder = OkHttpClient.Builder()
            .connectTimeout(5L, TimeUnit.SECONDS)
//            .addInterceptor(ReceivedCookiesInterceptor()) // 先获取 Cookie
            .addInterceptor(AddCookiesInterceptor()) // 再添加 Cookie
        return okBuilder.build()
    }

    suspend fun readRfid(data: String,callback: (RfidBean) -> Unit){
        apiService?.rfid(data)?.enqueueWithCallback (
            onSuccess = {rfid->
                LogUtils.e(rfid.toString())
                callback(rfid)
            },
            onError = {}
        )
    }

    /**
     * 创建流程
     */

    suspend fun createNote(
         type: Int = 0,
         flowId: Int =0,
         callback: (CreateNote) -> Unit
     ) {
        try {
            apiService?.createNote(type = type,flowId = flowId)?.enqueueWithCallback(
                onSuccess = { createNote ->
                    if (createNote.type != 0) {
                        LogUtils.e(createNote.toString())

                        callback(createNote)
                    } else {
                        // 处理错误情况
                        ToastUtils.showShort("创建流程失败")
//                        throw IOException(createNote.type.toString())
                    }
                },
                onError = { errorMsg ->
                    ToastUtils.showShort("服务器异常")
//                    throw IOException(errorMsg)
                }
            )
        } catch (e: Exception) {
            e.printStackTrace()
//            throw IOException(e.message)
            ToastUtils.showShort("服务器异常")

        }
    }

    /**
     * 更新流程
     */
    suspend fun updateNote(
        id: Int = 0,
        type: String? = null,
        result: String? = null,
        callback: (UpdateNote) -> Unit
    )   {
        try {
            apiService?.updateNote(
                id = id,
                type = type,
                result = result,
            )?.enqueueWithCallback(
                onSuccess = { updateNote ->
                    if (updateNote.type != 0) {
                        LogUtils.e(updateNote.toString())

                        callback(updateNote)
                    } else {
                        // 处理错误情况
                        ToastUtils.showShort("更新流程失败")
//                        throw IOException(updateNote.type.toString())
//                        UartUtil.onDataSend("{\"cmd\":\"control\",\"dianji\":{\"yd\":\"H\"}}")
                    }
                },
                onError = { errorMsg ->
                    //
                    // 处理错误情况
                    ToastUtils.showShort("服务器异常")
                    LogUtils.e(errorMsg.toString())
                    //throw IOException(errorMsg.toString())
                }
            )
        } catch (e: Exception) {
            e.printStackTrace()
            ToastUtils.showShort("服务器异常")

//            throw IOException(e.message)
        }
    }

    /**
     * 设备初始化数据
     */
    suspend fun deviceData(
        version: String? = null,
        callback: (DeviceInitData) -> Unit
    )   {
        try {
            apiService?.versionNote(
                version = version,
            )?.enqueueWithCallback(
                onSuccess = { deviceData ->
                    if (deviceData.status == "200") {
                        callback(deviceData)
                    } else {
                        // 处理错误情况
                        ToastUtils.showShort("设备初始化数据失败")
//                        throw IOException(deviceData.msg)
                    }
                },
                onError = { errorMsg ->
                    ToastUtils.showShort("服务器异常")
//                    throw IOException(errorMsg)
                }
            )
        } catch (e: Exception) {
            e.printStackTrace()
            ToastUtils.showShort("服务器异常")
//            throw IOException(e.message)
        }
    }
}